﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        const string FileName = @"..\..\SavedLoan.bin";
        private LoanClass.Loan TestLoan = new LoanClass.Loan(10000.0, 0.075, 36, "Neil Black");
        public MainWindow()
        {
            InitializeComponent();
        }

        private void CustomerPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            MessageBox.Show(e.PropertyName + " has been changed.");
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (File.Exists(FileName))
                {
                    Stream TestFileStream = File.OpenRead(FileName);
                    BinaryFormatter deserializer = new BinaryFormatter();
                    TestLoan = (LoanClass.Loan)deserializer.Deserialize(TestFileStream);
                    TestFileStream.Close();
                }

                TestLoan.PropertyChanged += this.CustomerPropertyChanged;

                textBox1.Text = TestLoan.LoanAmount.ToString();
                textBox2.Text = TestLoan.InterestRate.ToString();
                textBox3.Text = TestLoan.Term.ToString();
                textBox4.Text = TestLoan.Customer;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                TestLoan.LoanAmount = Convert.ToDouble(textBox1.Text);
                TestLoan.InterestRate = Convert.ToDouble(textBox2.Text);
                TestLoan.Term = Convert.ToInt32(textBox3.Text);
                TestLoan.Customer = textBox4.Text;

                Stream TestFileStream = File.Create(FileName);
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(TestFileStream, TestLoan);
                TestFileStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}
